package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.model.common.admin.dto.AdminLoginDto;
import com.zhentao.model.common.admin.pojo.AdminUser;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.AdminUserService;
import com.zhentao.mapper.AdminUserMapper;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;

/**
* @author liu
* @description 针对表【admin_user】的数据库操作Service实现
* @createDate 2024-09-26 10:44:50
*/
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser>
    implements AdminUserService{
    @Resource
    private AdminUserMapper adminUserMapper;


    @Override
    public ResponseResult addLogin(AdminLoginDto loginDto) {
        //校验是否为空
        if (StringUtils.isBlank(loginDto.getName()) || StringUtils.isBlank(loginDto.getPassword()) ){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据登录用户名进行查找是否存在
        AdminUser adminUser = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getUsername, loginDto.getName()));

        if (adminUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (adminUser.getState()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"账号被禁用，请联系管理员");
        }



        //获取盐
        String salt = adminUser.getSalt();
        //获取正确密码
        String password = adminUser.getPassword();

        //将用户登录的密码进行使用MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));

        //进行比对密码
        if (!password.equals(md5Pass)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }


        //更新登录时间
        adminUser.setNewLoginTime(new Date());
        adminUserMapper.updateById(adminUser);

        //生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adminUser.getAdminUserId()));
        //创建map集合
        HashMap<String, Object> map = new HashMap<>();
        //将token放入集合当中
        map.put("token",token);

        //将用户信息放入map当中
        adminUser.setPassword(null);
        adminUser.setSalt(null);
        map.put("adminLoginUser",adminUser);

        return ResponseResult.okResult(map);
    }
}




